﻿using AutoMapper;
using B.S.BaseData.Api.Read.Command.RBAC;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;
using B.S.BataBase.Domain.DTO;
using B.S.BataBase.Domain.RBAC;
using MediatR;

namespace B.S.BaseData.Api.Read.CommandHandler.RBAC
{
    public class PathShowCommandHandler : IRequestHandler<PathShowCommand, APIResult<List<PathDTO>>>
    {
        private readonly IBaseRepository<RoleModel> _rolerepository;
        private readonly IBaseRepository<RolePermissionsModel> _rolepubrolerepository;
        private readonly IBaseRepository<PermissionsModel> _permissrepository;
        private readonly IMapper _mapper;
        public PathShowCommandHandler(IBaseRepository<RoleModel> rolerepository, IBaseRepository<RolePermissionsModel> rolepubrolerepository, IMapper mapper, IBaseRepository<PermissionsModel> permissrepository)
        {
            _rolerepository = rolerepository;
            _rolepubrolerepository = rolepubrolerepository;
            _mapper = mapper;
            _permissrepository = permissrepository;
        }
        public async Task<APIResult<List<PathDTO>>> Handle(PathShowCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<PathDTO>> result = new APIResult<List<PathDTO>>();
            List<PathDTO> pathList = new List<PathDTO>();   

            foreach(var item in request.Paths)
            {
                var list = _rolepubrolerepository.GetAll().Where(x=>x.RoleId==item).ToList();
                foreach (var ids in list)
                {
                    var data = await _permissrepository.GetValues(x=>x.Id==ids.PermissionsId);
                    PathDTO dTO = new PathDTO();
                    dTO.Path = data.Addr;
                    dTO.Name = data.PermissionsName;
                    pathList.Add(dTO);
                }
            }
            pathList = pathList.DistinctBy(x=>x.Name).ToList();

            result.Code = ApiEnum.Success;
            result.Msg = "权限菜单显示成功";
            result.Data = pathList;
            return result;
        }
    }
}
